package services

import (
	"context"
	"fmt"

	"baseService/internal/domain/entities"
	"baseService/internal/domain/repositories"
	pkglogger "baseService/internal/pkg/logger"

	"gorm.io/gorm"
)

// UserService 提供用户业务操作
type UserService struct {
	repo   repositories.UserRepository
	logger pkglogger.Logger
}

// NewUserService 创建用户服务实例
func NewUserService(repo repositories.UserRepository, logger pkglogger.Logger) *UserService {
	return &UserService{
		repo:   repo,
		logger: logger,
	}
}

// ListUsers 返回基于查询条件的用户列表
func (s *UserService) ListUsers(ctx context.Context, options *repositories.QueryOptions) ([]*entities.User, int64, error) {
	users, total, err := s.repo.List(ctx, options)
	if err != nil {
		return nil, 0, err
	}
	return users, total, nil
}

// GetUser 获取单个用户
func (s *UserService) GetUser(ctx context.Context, id uint) (*entities.User, error) {
	user, err := s.repo.GetByID(ctx, id)
	if err != nil {
		return nil, err
	}
	return user, nil
}

// CreateUser 创建用户
func (s *UserService) CreateUser(ctx context.Context, user *entities.User) error {
	if _, err := s.repo.GetByUsername(ctx, user.Username); err == nil {
		return fmt.Errorf("username already exists")
	} else if err != nil && err != gorm.ErrRecordNotFound {
		return err
	}

	if user.Status == 0 {
		user.Status = 1
	}

	return s.repo.Create(ctx, user)
}

// UpdateUser 更新用户
func (s *UserService) UpdateUser(ctx context.Context, id uint, fields map[string]interface{}) error {
	if len(fields) == 0 {
		return nil
	}
	return s.repo.Update(ctx, id, fields)
}

// DeleteUser 删除用户
func (s *UserService) DeleteUser(ctx context.Context, id uint) error {
	if err := s.repo.Delete(ctx, id); err != nil {
		return err
	}
	return nil
}

// EnsureUserExists 校验用户是否存在
func (s *UserService) EnsureUserExists(ctx context.Context, id uint) error {
	_, err := s.repo.GetByID(ctx, id)
	return err
}
